package com.teacold.customdemo.chapter_one;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.RegionIterator;
import android.util.AttributeSet;
import android.view.View;

import com.teacold.customdemo.R;

public class ClipRgnView extends View {
    private Bitmap mBitmap;
    private int clipWith = 0;
    private int width;
    private int height;
    private static final int CLIP_HEIGHT = 30;
    private Region mRegion;

    public ClipRgnView(Context context) {
        super(context);
        init();
    }

    public ClipRgnView(Context context, AttributeSet attrs) {
        this(context);
    }

    public ClipRgnView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs);
    }

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.timg);
        width = mBitmap.getWidth();
        height = mBitmap.getHeight();
        mRegion = new Region();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        clipRgn(canvas);

    }

    private void clipRgn(Canvas canvas) {
        mRegion.setEmpty();
        int i = 0;
        while (i * CLIP_HEIGHT <= height) {
            if (i % 2 == 0) {
                mRegion.union(new Rect(0, i * CLIP_HEIGHT, clipWith, (i + 1) * CLIP_HEIGHT));
            } else {
                mRegion.union(new Rect(width - clipWith, i * CLIP_HEIGHT, width, (i + 1) * CLIP_HEIGHT));
            }
            i++;
        }
        clipRegion(canvas,mRegion);
        canvas.drawBitmap(mBitmap, 0, 0, new Paint());
        if(clipWith>width){
            return;
        }
         clipWith+=5;
        invalidate();
    }

    private void clipRegion(Canvas canvas,Region mRegion) {
        RegionIterator regionIterator=new RegionIterator(mRegion);
        Rect rect=new Rect();
        while (regionIterator.next(rect)){
            canvas.drawRect(rect,new Paint());
        }
    }


}
